package com.erb.controller.zwj.admin;

import com.erb.constants.AdminProductConstants;
import com.erb.constants.AdminRedpacketConstants;
import com.erb.entity.Pager;
import com.erb.entity.Redenvelopes;
import com.erb.entity.RespBean;
import com.erb.service.zwj.IAdminRedpacketService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 红包管理模块
 */
@Controller
@RequestMapping("/admin/redpacket")
public class AdminRedpacketController {
	@Resource
	private IAdminRedpacketService adminRedpacketService;

	private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");

	@GetMapping("/list")
	public String list(Model model, Pager pager) {
		model.addAttribute("pager", pager);
		// 红包类型
		model.addAttribute("rtypeMap", AdminRedpacketConstants.REPACKET_RTYPE_MAP);
		// 红包状态
		model.addAttribute("stateMap", AdminRedpacketConstants.REPACKET_STATE_MAP);
		// 项目类型
		model.addAttribute("ptypeMap", AdminProductConstants.PRODUCT_TYPE_MAP);
		// 当前时间
		model.addAttribute("minTime", dateFormat.format(new Date(System.currentTimeMillis())));
		return "admin/redpacket/list";
	}

	// 查询红包列表
	@ResponseBody
	@GetMapping("/listJson")
	public RespBean listJson(Pager pager) {
		return RespBean.ok("查询成功！", adminRedpacketService.findAll(pager));
	}

	// 查看单个红包详细信息
	@ResponseBody
	@GetMapping("/{id}")
	public RespBean get(@PathVariable("id") Integer id) {
		try {
			return RespBean.ok("查询成功！", adminRedpacketService.findRedpacket(id));
		} catch (Exception e) {
			return RespBean.error("红包不存在！");
		}
	}

	// 删除红包
	@ResponseBody
	@PostMapping("/remove/{id}")
	public RespBean remove(@PathVariable("id") Integer id) {
		try {
			return RespBean.ok("删除成功！", adminRedpacketService.removeRedpacket(id));
		} catch (Exception e) {
			return RespBean.error("红包不存在！");
		}
	}

	// 保存红包信息
	@ResponseBody
	@PostMapping("/save")
	public RespBean save(Redenvelopes redenvelopes, String startTimeStr, String endTimeStr) {
		if (ObjectUtils.isEmpty(redenvelopes)) {
			return RespBean.error("错误请求！");
		}

		try {// 设置红包可使用的开始时间 ~ 结束时间
			redenvelopes.setStartTime(new Timestamp(dateFormat.parse(startTimeStr).getTime()));
			redenvelopes.setEndTime(new Timestamp(dateFormat.parse(endTimeStr).getTime()));
		} catch (ParseException e) {
			e.printStackTrace();
		}

		try {
			return RespBean.ok("保存成功！", adminRedpacketService.saveRedpacket(redenvelopes));
		} catch (Exception e) {
			e.printStackTrace();
			return RespBean.error("保存失败！");
		}
	}
}
